package javase2.day04;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class Homework {
	public static void split(String file, int size) {
		try {
			InputStream in = new FileInputStream(file);
			OutputStream output;
			byte[] buf = new byte[size];
			int i;
			int j = 1;
			while ((i = in.read(buf)) != -1) {
				File file2 = new File("/home/tarena/split/" + j + ".txt");
				output = new FileOutputStream(file2);
				output.write(buf, 0, i);
				j++;
				//output.close();
			}
			in.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new RuntimeException();
		}
	}

	public static void join(String file){
		try {
			InputStream in;
			int i=1;
			int j;
			OutputStream out=new FileOutputStream(file);
			String file2;
			byte[] buf;
			while(true){
					file2="/home/tarena/split/"+i+".txt";
					File files = new File(file2);
					if(!files.exists()){
						break;
					}
					in = new FileInputStream(file2);
					buf=new byte[in.available()];
					i++;
					while((j=in.read(buf))!=-1){
						out.write(buf,0,j);
					}
					in.close();
			}
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

	public static void main(String[] args) {
		String file = "/home/tarena/hotel.txt";
		split(file, 30);
		String file2 = "/home/tarena/split/demo.txt";
		join(file2);
	}
}
